package com.gwcloud.leetcode.hot100;

/** 
* @ClassName   : Leetcode0034 
* @author      : ganwei 
* @date        : 2020年5月14日 
* @Description : 在排序数组中查找元素的第一个和最后一个位置 
*/
public class Leetcode0034 {
	/**
	 * -解题思路，二分查找
	 */
    public int[] searchRange(int[] nums, int target) {
    	int left = 0, right = nums.length-1;
    	int index = -1;
    	while(left <= right) {
    		int mid = left + (right-left)/2;
    		if(nums[mid] == target) {
    			index = mid;
    		}
    		if(nums[mid] > target) {
    			right = mid - 1;
    		}else {
    			left = mid + 1;
    		}
    	}
    	System.out.println(index);
    	if(index == -1) {
    		int[] indexs = {-1,-1};
    		return indexs;
    	}else {
    		int i = index, j = index;
    		while(i>=0 && nums[i] == target) {
    			i--;
    		}
    		
    			i++;
    		
    		while(j < nums.length && nums[j] == target) {
    			j++;
    		}

    		j--;
    		
    		int[] indexs = {i,j};
    		return indexs;
    	}
    	
    }
    
    public static void main(String[] args) {
    	Leetcode0034 l0034 = new Leetcode0034();
    	int[] nums = {1,4};
    	for(int i :l0034.searchRange(nums, 4)) {
    		System.out.println(i);
    	}

    }
}
